package main

import (
	"fmt"
	"io"
	"net"
	"os"
)

func sendFile(conn net.Conn, path string)  {
	buf:=make([]byte,1024*4)
	f,err:=os.Open(path)
	defer f.Close()
	if err!=nil {
		fmt.Println("err Open:",err)
		return
	}
	for{
		n,errRead:=f.Read(buf)
		if errRead!=nil{
			if errRead==io.EOF{
				fmt.Println("文件传输完毕")
			}else{
				fmt.Println("errRead:",errRead)
			}
			return
		}
		conn.Write(buf[:n])
	}

}
func main()  {
	fmt.Println("请输入要发送的文件")
	var path string
    _,err:=fmt.Scan(&path)
    if err!=nil{
    	fmt.Println("Scan err:",err)
		return
	}
    info,errStat := os.Stat(path)
    if errStat != nil{
    	fmt.Println("errStat:",errStat)
    	return
	}
    fmt.Println(info.Name(), info.Size())

    conn,errConn:= net.Dial("tcp","127.0.0.1:8000")
	defer conn.Close()
    if errConn!=nil{
    	fmt.Println("errConn",errConn)
    	return
	}

    _,errWrite := conn.Write([]byte(info.Name()))
    if errWrite!=nil{
    	fmt.Println("err Write:",errWrite)
    	return
	}

    buf:=make([]byte, 1024)
    n,errRead:=conn.Read(buf)
    if errRead!=nil{
    	fmt.Println("errRead:",errRead)
	}
    if "ok" == string(buf[:n]){
    	sendFile(conn,path)
	}
}
